package com.aibili.contoller.api;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.aibili.common.JPushUtil;
import com.aibili.pojo.MomentClick;
import com.aibili.pojo.MomentComment;
import com.aibili.pojo.MomentInfo;
import com.aibili.pojo.MomentShare;
import com.aibili.pojo.NoticeInfo;
import com.aibili.pojo.UserDevice;
import com.aibili.pojo.UserInfo;
import com.aibili.service.FileService;
import com.aibili.service.MomentService;
import com.aibili.service.NoticeInfoService;
import com.aibili.service.UserDeviceService;
import com.aibili.service.UserInfoService;
import com.alibaba.fastjson.JSON;
import com.daoshun.common.CommonUtils;
import com.daoshun.common.DsConstant;
import com.daoshun.exception.CustomException;

@Controller
@RequestMapping("/api/moment")
public class ApiMomentContoller extends ApiBaseContoller {

	@Resource
	private MomentService monentService;

	@Resource
	private UserInfoService userInfoService;

	@Resource
	private FileService fileService;
	
	@Resource
	private NoticeInfoService noticeInfoService;
	
	@Resource
	private UserDeviceService userDeviceService;

	/**
	 * 发布动态
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/publish", produces = "application/json; charset=UTF-8")
	public String publish(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			// 用户id
			String user_id = request.getParameter("user_id");
			// 内容
			String content = request.getParameter("content");
			//String picNum = request.getParameter("pic_num");
			// 图片的id “，”分割
//			String pic_ids = request.getParameter("pic_ids");
			CommonUtils.validateEmpty(user_id);
			MomentInfo momentinfo = new MomentInfo();
			// 取用户
			UserInfo user = userInfoService.getById(CommonUtils.parseLong(user_id, 0));
			if (user == null) {
				map.put("message", DsConstant.NO_USER);
				return DsConstant.NO_USER;
			}
			momentinfo.setUser(user);
			momentinfo.setContent(content);
			momentinfo.setCreate_time(new Date());
			//int pic_num = CommonUtils.parseInt(picNum, 0);
			int real_num = 0;
			// 取图片地址
			String pics = "";
//			if (!CommonUtils.isEmptyString(pic_ids)) {
//				String[] picstr = pic_ids.split(",");
//				if (picstr != null && picstr.length > 0) {
//					for (String str : picstr) {
//						FileInfo fileinfo = monentService.getFileInfoById(CommonUtils.parseLong(str, 0));
//						if (fileinfo != null) {
//							real_num ++;
//							if (CommonUtils.isEmptyString(pics)) {
//								pics = fileinfo.getFile_name();
//							} else {
//								pics += "," + fileinfo.getFile_name();
//							}
//						}
//					}
//				}
//			}
			String video = "";
			// 创建一个通用的多部分解析器
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			// 判断 request 是否有文件上传,即多部分请求
			if (multipartResolver.isMultipart(request)) {
				// 转换成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				// 取得request中的所有文件名
				Iterator<String> iter = multiRequest.getFileNames();
				try {
					while (iter.hasNext()) {
						// 取得上传文件
						MultipartFile file = multiRequest.getFile(iter.next());
						if (file != null) {
							// 取得当前上传文件的文件名称
							String myFileName = file.getOriginalFilename();
							// 如果名称不为“”,说明该文件存在，否则说明该文件不存在
							if (!CommonUtils.isEmptyString(myFileName)) {
								if (myFileName.contains(".avi") || myFileName.contains(".rmvb")
										|| myFileName.contains(".rm") || myFileName.contains(".asf")
										|| myFileName.contains(".divx") || myFileName.contains(".mpg")
										|| myFileName.contains(".mpeg") || myFileName.contains(".mpe")
										|| myFileName.contains(".wmv") || myFileName.contains(".mp4")
										|| myFileName.contains(".mkv") || myFileName.contains(".vob") 
										|| myFileName.contains(".mov")) {
									video = fileService.saveFile(file);
								} else {
									String filePath = fileService.saveImage(file);
									if (CommonUtils.isEmptyString(pics)) {
										pics = filePath;
									} else {
										pics += "," + filePath;
									}
									real_num ++;
								}
							}
						}
					}
				} catch (Exception e) {
					return "";
				}
			}
			
			//pic_num = real_num;
			momentinfo.setPics(pics);
			//momentinfo.setPic_num(pic_num);
			momentinfo.setVideo(video);
			momentinfo.setPraise_num(0);
			momentinfo.setStatus(0);
			momentinfo.setChioce(0);
			// 添加动态信息
			monentService.SaveMomentInfo(momentinfo);
			map.putAll(DsConstant.SUCCESS_RESULT_MAP);
			return JSON.toJSONString(map);
		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}
	}

	/**
	 * 点赞
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/praise", produces = "application/json; charset=UTF-8")
	public String praise(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			// 用户id
			String user_id = request.getParameter("user_id");
			// 动态id
			String moment_id = request.getParameter("moment_id");
			CommonUtils.validateEmpty(user_id);
			CommonUtils.validateEmpty(moment_id);
			long uid = CommonUtils.parseLong(user_id, 0);
			long mid = CommonUtils.parseLong(moment_id, 0);
			// 判断用户是否点过赞
			MomentClick click = monentService.getMomentClickByUseridMomentid(uid, mid);
			if (click != null) {
				return DsConstant.CLICK_EXIST;
			} else {
				// 根据id取动态信息
				MomentInfo momentinfo = monentService.getMonentInfo(mid);
				if (momentinfo != null) {
					momentinfo.setPraise_num(momentinfo.getPraise_num() + 1);
					momentinfo.setIsclick(1);
					// 更新动态
					monentService.updateMomentInfo(momentinfo);
					
					MomentClick click1 = new MomentClick();
					click1.setMoment_id(mid);
					click1.setUser_id(uid);
					
					monentService.addMomentClick(click1);
					
					map.putAll(DsConstant.SUCCESS_RESULT_MAP);
					return JSON.toJSONString(map);
				} else {
					return DsConstant.NO_MOMENT;
				}
			}
			
		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}
	}

	/**
	 * 评论
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/comment", produces = "application/json; charset=UTF-8")
	public String comment(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			// 用户id
			String user_id = request.getParameter("user_id");
			// 动态id
			String moment_id = request.getParameter("moment_id");
			// 评论内容
			String content = request.getParameter("content");
			// 被提到的好友的id
			String mention_id = request.getParameter("mention_id");
			CommonUtils.validateEmpty(user_id);
			CommonUtils.validateEmpty(moment_id);
			CommonUtils.validateEmpty(content);
			//CommonUtils.validateEmpty(mention_id);
			long momid = CommonUtils.parseLong(moment_id, 0);
			long uid = CommonUtils.parseLong(user_id, 0);
			//long mentionid = CommonUtils.parseLong(mention_id, 0);
			UserInfo user = userInfoService.getById(uid);
			if (user != null) {
				MomentComment comment = new MomentComment();
				comment.setContent(content);
				comment.setCreate_time(new Date());
				comment.setMoment_id(momid);
				comment.setUser(user);
				if (!CommonUtils.isEmptyString(mention_id)) {
					long mentionid = CommonUtils.parseLong(mention_id, 0);
					comment.setMention_id(mentionid);
				}
				// 添加动态评论
				monentService.SaveMomentComment(comment);
				//加经验
				monentService.addexpBycomment(uid,momid);
				// 消息推送
				NoticeInfo notice = new NoticeInfo();
				// 被评论的人的id
				// 通过动态去找
				MomentInfo info = monentService.getMonentInfo(momid);
				
				if (info != null && user.getId()!=info.getUser().getId()) {
					notice.setFrom_id(info.getUser().getId());
				notice.setUser_id(user.getId());
				notice.setPortrait(user.getPortrait()); // 评论人的头像
				notice.setTitle("你收到了一条评论！");
				notice.setContent(user.getUser_name() + "评论了你的动态！");
				notice.setPublish_time(new Date());
				notice.setMoment_id(info.getId());
			
				noticeInfoService.addNoticeInfo(notice);
				// 发送推送给被评论的人
				// 找到设备信息
				JPushUtil jpush = new JPushUtil();
				List<UserDevice> devices = userDeviceService.getByUserid(info.getUser().getId());
				for (UserDevice userDevice : devices) {
					if (userDevice.getType() == 0) {
						jpush.sendSingleAndroidPush(userDevice.getClient_id(), user.getUser_name() + "评论了你的动态！");
					} else {
						jpush.sendSingleIOSPush(userDevice.getClient_id(), user.getUser_name() + "评论了你的动态！", null);
					}
				}
				
				//发送消息给被@的人
				if (!CommonUtils.isEmptyString(mention_id)){
					long mentionid = CommonUtils.parseLong(mention_id, 0);
					UserInfo muser = userInfoService.getById(mentionid);
					if (muser!=null) {
						NoticeInfo noticem = new NoticeInfo();
						noticem.setFrom_id(muser.getId());
						noticem.setUser_id(user.getId());
						noticem.setPortrait(user.getPortrait());
						noticem.setTitle("你收到了一条通知！");
						noticem.setContent(user.getUser_name() + "提到了你！");
						noticem.setPublish_time(new Date());
						noticem.setMoment_id(info.getId());
						noticeInfoService.addNoticeInfo(noticem);
						
						JPushUtil mjpush = new JPushUtil();
						List<UserDevice> mdevices = userDeviceService.getByUserid(muser.getId());
						for (UserDevice userDevice : mdevices) {
							if (userDevice.getType() == 0) {
								mjpush.sendSingleAndroidPush(userDevice.getClient_id(), user.getUser_name() + "提到了你！");
							} else {
								mjpush.sendSingleIOSPush(userDevice.getClient_id(), user.getUser_name() + "提到了你！", null);
							}
						}
					}
				}
				}
				map.putAll(DsConstant.SUCCESS_RESULT_MAP);
				return JSON.toJSONString(map);
			} else {
				return DsConstant.NO_USER;
			}
		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}
	}

	/**
	 * 评论列表
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/comment_list", produces = "application/json; charset=UTF-8")
	public String comment_list(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			// 动态id
			String moment_id = request.getParameter("moment_id");
			String page = request.getParameter("page");
			CommonUtils.validateEmpty(moment_id);
			if (CommonUtils.isEmptyString(page)) {
				page = "1";
			}
			// 根据动态id取动态评论
			List<MomentComment> comment_list = monentService.getMomentCommentListByMomment(
					CommonUtils.parseLong(moment_id, 0), CommonUtils.parseInt(page, 0), DsConstant.PAGESIZE);
			map.put("comment_list", comment_list);
			map.putAll(DsConstant.SUCCESS_RESULT_MAP);
			return toJson(map);
		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}
	}

	/**
	 * 动态列表
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/list", produces = "application/json; charset=UTF-8")
	public String list(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			String user_id = request.getParameter("user_id");
			String page = request.getParameter("page");
			CommonUtils.validateEmpty(user_id);
			if (CommonUtils.isEmptyString(page)) {
				page = "1";
			}
			// 分页取动态
			List<MomentInfo> moment_list = monentService.getMomentListByPage(CommonUtils.parseInt(page, 0),
					DsConstant.PAGESIZE, CommonUtils.parseLong(user_id, 0));
			int amount = moment_list.size();
			map.put("amount", amount);
			map.put("moment_list", moment_list);
			map.putAll(DsConstant.SUCCESS_RESULT_MAP);
			return toJson(map);
		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}
	}

	/**
	 * 我的动态列表
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/mine", produces = "application/json; charset=UTF-8")
	public String mine(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			// 用户id
			String user_id = request.getParameter("user_id");
			CommonUtils.validateEmpty(user_id);
			String page = request.getParameter("page");
			if (CommonUtils.isEmptyString(page)) {
				page = "1";
			}
			// 根据用户取动态列表
			List<MomentInfo> moment_list = monentService.getMomentListByUserInfo(CommonUtils.parseLong(user_id, 0),
					CommonUtils.parseInt(page, 0), DsConstant.PAGESIZE);
			map.put("moment_list", moment_list);
			map.putAll(DsConstant.SUCCESS_RESULT_MAP);
			return toJson(map);
		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}
	}
	
	/**
	 * 动态详情
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/detail", produces = "application/json; charset=UTF-8")
	public String detail(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			// 动态id
			String moment_id = request.getParameter("moment_id");
			String user_id = request.getParameter("user_id");
			CommonUtils.validateEmpty(moment_id);
			CommonUtils.validateEmpty(user_id);
			//取动态并判断是否点赞和评论数
			MomentInfo moment = monentService.getMonentInfoCC(CommonUtils.parseLong(moment_id, 0), CommonUtils.parseLong(user_id, 0));
			map.put("moment", moment);
			map.putAll(DsConstant.SUCCESS_RESULT_MAP);
			return toJson(map);
		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}
	}
	
	/**
	 * 
	 * @Description 删除动态
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/delete_moment", produces = "application/json; charset=UTF-8")
	public String delete_moment(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			// 动态id
			String moment_id = request.getParameter("moment_id");
			String user_id = request.getParameter("user_id");
			CommonUtils.validateEmpty(moment_id);
			CommonUtils.validateEmpty(user_id);
			MomentInfo info = monentService.getMonentInfo(CommonUtils.parseLong(moment_id, 0));
			if (info != null) {
				if (user_id.equals(info.getUser().getId()+"")) {
					// 删除
					monentService.deleteMoment(info);
					return toSuccessJson(map);
				} else {
					return DsConstant.NOT_YOUR_COMENT;
				}
			} else {
				return DsConstant.EXCEPTION;
			}
			
		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}
	}

	@ResponseBody
	@RequestMapping(value = "/share", produces = "application/json; charset=UTF-8")
	public String share(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			// 动态id
			String moment_id = request.getParameter("moment_id");
			String user_id = request.getParameter("user_id");
			CommonUtils.validateEmpty(moment_id);
			CommonUtils.validateEmpty(user_id);
			MomentShare share = new MomentShare();
			share.setMoment_id(CommonUtils.parseLong(moment_id, 0));
			share.setUser_id(CommonUtils.parseLong(user_id, 0));
			share.setCreate_time(new Date());
			monentService.addMomentShare(share);
			map.putAll(DsConstant.SUCCESS_RESULT_MAP);
			return toJson(map);
		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}
	}
}
